package com.fc.redap.controller.api;

import com.alibaba.fastjson.JSONObject;
import com.fc.redap.controller.BaseController;
import com.fc.redap.dtos.ResponseJson;
import com.fc.redap.entity.BookedUserStatisticEntity;
import com.fc.redap.entity.ProjectBookedUserEntity;
import com.fc.redap.entity.ProjectEntity;
import com.fc.redap.exception.ResponseException;
import com.fc.redap.helper.DateTimeHelper;
import com.fc.redap.service.IProjectBookedUserService;
import com.fc.redap.service.IProjectService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.websocket.server.PathParam;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/project/booked")
@Api(value="预约旅游项目的联系人相关的API", tags={"旅游项目预约"})
public class ProjectBookedUserController extends BaseController {

    @Autowired
    private IProjectBookedUserService projectBookedUserService;

    @Autowired
    private IProjectService projectService;

    @ApiOperation(value = "POST -- 获取项目已预定用户列表",
            notes = " REST 方式请求。"+
                    "Request Parameter: <ul>" +
                    "<li><i>必填参数: projectId: 项目ID</i></li>" +
                    "<li><i>可选参数: userId: 用户ID</i></li>" +
                    "<li><i>可选参数: contactPhone: 预订电话号码</i></li>" +
                    "<li><i>可选参数: count: 每页记录数, 默认10</i></li>" +
                    "<li><i>可选参数: page: 第几页, 从0开始</i></li>" +
                    "</ul>",
            response = ResponseJson.class,
            httpMethod = "POST",
            consumes = "application/json",
            produces = "application/json",
            code = 200
    )
    @PostMapping("/list")
    public ResponseJson doQueryList(@RequestBody JSONObject params) {

        params.put("limit",params.get("count"));
        params.put("offset",params.get("page"));
        //校对并赋值 offset和limit
        calculatePagination(params);

        List<ProjectBookedUserEntity> bookedUserEntityList = projectBookedUserService.queryList(params);
        return ResponseJson.success(bookedUserEntityList);
    }

    @PostMapping("/history")
    public ResponseJson doQueryHistoryList(@RequestBody JSONObject params) {

        params.put("limit",params.get("count"));
        params.put("offset",params.get("page"));
        //校对并赋值 offset和limit
        calculatePagination(params);

        List<ProjectBookedUserEntity> bookedUserEntityList = projectBookedUserService.queryHistoryList(params);
        return ResponseJson.success(bookedUserEntityList);
    }

    @PostMapping("/stat")
    public ResponseJson doStatistic(@RequestBody JSONObject params) {
        BookedUserStatisticEntity statistic = projectBookedUserService.statisticData(params);
        return ResponseJson.success(statistic);
    }

    @ApiOperation(value = "POST -- 保存预约红色旅游项目",
            notes = " REST 方式请求" +
                    "Request Body: <ul>" +
                    "<li><i>必填参数：projectId: 项目id</i></li>" +
                    "<li><i>必填参数：userId: 景区地点ID</i></li>" +
                    "<li><i>必填参数：contactName: 预定人姓名</i></li>" +
                    "<li><i>必填参数：contactPhone: 预定联系方式</i></li>" +
                    "<li><i>必填参数：bookedNumber: 预定位数</i></li>" +
                    "<li><i>可选参数：remark: 备注</i></li>" +
                    "</ul>",
            response = ResponseJson.class,
            httpMethod = "POST",
            consumes = "application/json",
            produces = "application/json",
            code = 200
    )
    @PostMapping("/save")
    public ResponseJson doSave(@RequestBody ProjectBookedUserEntity projectBookedUserEntity) {
        if(projectBookedUserEntity.getProjectId() == null)
        {
            throw new ResponseException("projectId不能为空!");
        }
        if(StringUtils.isEmpty(projectBookedUserEntity.getContactName()))
        {
            throw new ResponseException("姓名不能为空!");
        }
        if(StringUtils.isEmpty(projectBookedUserEntity.getContactPhone()))
        {
            throw new ResponseException("联系电话不能为空!");
        }

        ProjectEntity projectEntity = projectService.queryObject(projectBookedUserEntity.getProjectId());
        if(projectEntity == null)
        {
            throw new ResponseException("线路或场馆编号不正确, 未找到旅游项目!");
        }

        if(projectEntity.getType() == 0){
            if(projectBookedUserEntity.getBookedNumber() == null || projectBookedUserEntity.getBookedNumber() < 3)
            {
                throw new ResponseException("旅游线路报名人数不能为空且必须大于等于3!");
            }
        }else{
            if(projectBookedUserEntity.getBookedNumber() == null || projectBookedUserEntity.getBookedNumber() < 1)
            {
                throw new ResponseException("场馆报名人数不能为空且必须大于等于1!");
            }
        }

        //获取当天的预定情况
        Map<String, Object> params = new HashMap<>();
        params.clear();
        params.put("projectId", projectBookedUserEntity.getProjectId());
        params.put("bookedTime", DateTimeHelper.getStringFromDate(projectBookedUserEntity.getBookedTime(),DateTimeHelper.PAYLOAD_DATEONLY));
        List<ProjectBookedUserEntity> bookedUserEntityList = projectBookedUserService.queryBookeUserList(params);

        //红游景点一般是旅行团报名，一天一团
        if(projectEntity.getType() == 0){
            if(bookedUserEntityList != null && bookedUserEntityList.size()>0){
                throw new ResponseException("亲，该天名额已满，请选其他时间报名哦");
            }
        }else{
            if(bookedUserEntityList != null && bookedUserEntityList.size()>0 && bookedUserEntityList.size()>projectEntity.getLimitNumber()){
                throw new ResponseException("亲，该天名额已满，请选其他时间报名哦");
            }
        }

        for(ProjectBookedUserEntity user: bookedUserEntityList){
            if(user.getContactPhone()!=null && projectBookedUserEntity.getContactPhone()!=null && projectBookedUserEntity.getContactPhone().equals(user.getContactPhone())){
                throw new ResponseException("亲,你已经报过名了，不要重复报名哦");
            }
        }

        projectBookedUserEntity.setProjectName(projectEntity.getProjectName());
        projectBookedUserEntity.setCreateTime(DateTimeHelper.getCurrentDay());
        projectBookedUserEntity.setTouchStatus(1);
        projectBookedUserService.save(projectBookedUserEntity);
        return ResponseJson.success();
    }

    @ApiOperation(value = "PUT -- 更新预约红色旅游项目",
            notes = " REST 方式请求" +
                    "Request Body: <ul>" +
                    "<li><i>必填参数：projectId: 项目id</i></li>" +
                    "<li><i>必填参数：userId: 景区地点ID</i></li>" +
                    "<li><i>可选参数：contactName: 预定人姓名</i></li>" +
                    "<li><i>可选参数：contactPhone: 预定联系方式</i></li>" +
                    "<li><i>可选参数：bookedNumber: 预定位数</i></li>" +
                    "<li><i>可选参数：remark: 备注</i></li>" +
                    "</ul>",
            response = ResponseJson.class,
            httpMethod = "PUT",
            consumes = "application/json",
            produces = "application/json",
            code = 200
    )
    @PutMapping("/update")
    public ResponseJson doUpdate(@RequestBody ProjectBookedUserEntity projectBookedUserEntity) {
        projectBookedUserEntity.setCreateTime(DateTimeHelper.getCurrentDay());
        projectBookedUserService.update(projectBookedUserEntity);
        return ResponseJson.success();
    }

    @ApiOperation(value = "POST -- 批量删除预约红色旅游项目",
            notes = " REST 方式请求" +
                    "Request Body: <ul>" +
                    "<li><i>必填参数：ids: 预约的红色旅游项目记录的ID的数组</i></li>" +
                    "</ul>")
    @PostMapping("/delete")
    public ResponseJson doDelete(@RequestBody Long[] ids) {
        projectBookedUserService.deleteBatch(ids);
        return ResponseJson.success();
    }

    @ApiOperation(value = "POST -- 根据项目ID删除预约红色旅游项目的预约人列表",
            notes = " REST 方式请求" +
                    "Request Body: <ul>" +
                    "<li><i>必填参数：projectId: 项目ID</i></li>" +
                    "</ul>")
    @PostMapping("/deletesByProjectId")
    public ResponseJson doDeleteByProjectId(@RequestBody Long projectId) {
        projectBookedUserService.deleteByProjectId(projectId);
        return ResponseJson.success();
    }

    @ApiOperation(value = "POST -- 获取未联络数量",
            response = ResponseJson.class,
            httpMethod = "PUT",
            consumes = "application/json",
            produces = "application/json",
            code = 200
    )
    @RequestMapping("/untouched")
    public ResponseJson doQueryUntouched() {
        Integer i = projectBookedUserService.getUntouchedUserNumber();
        Map<String, Integer> num = new HashMap<>();
        num.put("num",i);
        return ResponseJson.success(num);
    }

    @ApiOperation(value = "PUT -- touch置为1",
            notes = " REST 方式请求" +
                    "Request Body: <ul>" +
                    "<li><i>必填参数：id: id</i></li>" +
                    "</ul>",
            response = ResponseJson.class,
            httpMethod = "PUT",
            consumes = "application/json",
            produces = "application/json",
            code = 200
    )
    @PutMapping("/touch/{bookId}/status/{touchStatus}")
    public ResponseJson doTouch(@PathVariable("bookId") Long bookId, @PathVariable("touchStatus") Integer status)
    {
        ProjectBookedUserEntity projectBookedUserEntity = projectBookedUserService.queryObject(bookId);
        projectBookedUserEntity.setTouchStatus(status);
        projectBookedUserService.update(projectBookedUserEntity);
        return ResponseJson.success();
    }
}
